from django.http import HttpResponse
from ...models.chat_model import ChatModel
from ...models.api_keys import ApiKeys
from django.core.serializers import serialize
from ...utils.time_conversion import iso_to_times

import json


def model_list(request):
    '''
    参数：enable=1
    '''
    chatmodel_enable_str = request.GET.get('enable', None)
    if chatmodel_enable_str is not None:
        all_chatmodel = ChatModel.objects.filter(enabled=True)
    else:
        all_chatmodel = ChatModel.objects.all().order_by('sort_num')

    json_data_str = serialize('json', all_chatmodel)
    json_data = json.loads(json_data_str)

    data = []
    for i in range(len(json_data)):
        json_data[i]['fields']['id'] = json_data[i]['pk']

        # 数据处理
        created_at_second = iso_to_times(json_data[i]['fields']['created_at'])
        updated_at_second = iso_to_times(json_data[i]['fields']['updated_at'])
        json_data[i]['fields']['created_at'] = created_at_second
        json_data[i]['fields']['updated_at'] = updated_at_second

        # 连表查询key name
        if json_data[i]['fields']['key_id'] is None:
            json_data[i]['fields']['key_id'] = 0
            json_data[i]['fields']['key_name'] = ""
        else:
            json_data[i]['fields']['key_name'] = all_chatmodel[i].key_id.name

        data.append(json_data[i]['fields'])

    res_mes = {
        "code": 0,
        "data": data
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def model_save(request):
    '''
    save
    post
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        # 删除没必要的数据
        try:
            del json_obj['created_at']
            del json_obj['updated_at']
            del json_obj['last_used_at']
            del json_obj['key_name']
        except:
            pass

        if not json_obj['temperature']:
            del json_obj['temperature']
        else:
            pass


        # if json_obj['key_id'] is None or not json_obj['key_id']:
        #     del json_obj['key_id']
        if not json_obj['key_id']:
            json_obj['key_id'] = None

        # 查询数据
        if "id" in json_obj:
            chatmodel_instance_list = ChatModel.objects.filter(id=json_obj['id'])
            if chatmodel_instance_list:
                chatmodel_instance = chatmodel_instance_list[0]
            else:
                res_mes = {
                    "code": 1,
                    "message": "没有这个数据"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
        else:
            chatmodel_instance = ChatModel()

        # 保存数据
        for key, value in json_obj.items():
            if key == "key_id":
                if value is None or value == 0:
                    chatmodel_instance.key_id = None
                else:
                    apikey_instance = ApiKeys.objects.get(id=value)
                    chatmodel_instance.key_id = apikey_instance
            elif key == "max_context":
                print(value, 'dadsadsa')
                if value is None or not value:
                    all_mode_max_context = {
                        "gpt-3.5-turbo": 16384,
                        "gpt-3.5-turbo-16k": 16384,
                        "gpt-4": 8192,
                        "gpt-4o": 32768,
                        "gpt-4-turbo": 32768,
                        "gpt-4-32k": 32768,
                        "qwen-turbo": 8192,
                        "qwen-plus": 32768,
                    }
                    print(value, 'dadsadsa')
                    if value in all_mode_max_context:
                        chatmodel_instance.max_context = all_mode_max_context[value]
                    else:
                        # 默认设置为1024
                        chatmodel_instance.max_context = 8092
                else:
                    chatmodel_instance.max_context = value
            elif key == "max_tokens":
                if value is None or not value:
                    chatmodel_instance.max_tokens = 2048
            else:
                code_str = "chatmodel_instance.%s = '%s'" % (key, value)
                exec(code_str)

        try:
            chatmodel_instance.save()
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": e
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        # 返回这个实例的数据
        ok_chatmodel_instance = ChatModel.objects.get(name=json_obj['name'])
        
        data_str = serialize('json', [ok_chatmodel_instance])
        data = json.loads(data_str)
        chatmodel_str = data[0]["fields"]

        # 数据处理一下
        chatmodel_str['id'] = data[0]['pk']

        created_at_second = iso_to_times(chatmodel_str['created_at'])
        updated_at_second = iso_to_times(chatmodel_str['updated_at'])

        chatmodel_str['created_at'] = created_at_second
        chatmodel_str['updated_at'] = updated_at_second

        res_mes = {
            "code": 0,
            "data": chatmodel_str
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def model_remove(request):
    re_id = request.GET.get('id')
    try:
        del_obj = ChatModel.objects.get(id=re_id)
        del_obj.delete()

        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    except Exception as e:
        res_mes = {
            "code": 1,
            "message": e
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def model_set(request):
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        try:
            if json_obj['filed'] == "enabled":
                ChatModel.objects.filter(id=json_obj['id']).update(enabled=json_obj['value'])
            else:
                ChatModel.objects.filter(id=json_obj['id']).update(open=json_obj['value'])
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": e
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def model_sort(request):
    '''
    {
        "ids": [
            1,
            18,
            17,
            20
        ],
        "sorts": [
            1,
            2,
            3,
            4
        ]
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        try:
            for index, ids in enumerate(json_obj['ids']):
                ChatModel.objects.filter(id=ids).update(sort_num=json_obj['sorts'][index])
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": e
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

